package com.jbp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.AppConfigDao;
import com.jbp.model.AppConfig;
import com.jbp.model.Property;
import com.jbp.redis.RedisConfigService;
import com.jbp.service.AppConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;

import java.util.*;

/**
 * 应用设置(AppConfig)表服务实现类
 * @author cc
 * @since 2020-07-04 23:42:42
 */
@Service
public class AppConfigServiceImpl extends ServiceImpl<AppConfigDao, AppConfig> implements AppConfigService {
    @Autowired
    private RedisConfigService redisConfigService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<AppConfig> queryWrapper = new QueryWrapper<>();
        if (params.get("id") != null){
            queryWrapper.like("id",params.get("id"));
        }
        IPage<AppConfig> page = this.page(
                new Query<AppConfig>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public AppConfig getByKey(String key) {
        QueryWrapper<AppConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("param_key", key);
        return getOne(queryWrapper);
    }

    @Override
    public int getInt(String k) {
        String v = getVForCache(k);
        return v==null ? 0 :  Integer.parseInt(v);
    }

    @Override
    public String getV(String key) {
        AppConfig config = getByKey(key);
        return config == null ? null : config.getParamValue();
    }

    @Override
    public String getVForCache(String key) {
        //缓存10s
        long ttl = 1L * 30;
        String v = null;
        String k = "appconfig:"+key;
        if(redisConfigService.exists(k)) {
            v = (String) redisConfigService.get(k);
        } else {
            v = getV(key);
            redisConfigService.set(k, v, ttl);
        }
        return v;
    }

    @Override
    public List<AppConfig> appConfigList() {
        QueryWrapper<AppConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("param_key", Arrays.asList("event", "privacyAgreement","userAgreement","eventIcon","eventUrl","showPassRoom","tecent_sdkappid","agora_appid"));
        return list(queryWrapper);
    }

}